package com.lwphk.easydocs.ui;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.lwphk.easydocs.core.vo.ControllerInfo;
import com.lwphk.easydocs.core.vo.DocsBasicInfo;
import com.lwphk.easydocs.core.vo.MethodInfo;
import com.lwphk.easydocs.ui.vo.DocsUITreeData;

public class DocsUIHandler {

	private static final Logger log = LoggerFactory.getLogger(DocsUIHandler.class);

	public void data() {
		Map<String, ControllerInfo> m = DocsBasicInfo.ControllerInfoMap;

		List<MethodInfo> list = m.values().stream().flatMap(e -> e.getMethodInfos().stream())
				.collect(Collectors.toList());

		Map<String, List<MethodInfo>> methodInfoMap = list.stream()
				.collect(Collectors.groupingBy(e -> e.getParentDir().replaceAll("/", "")));


		List<DocsUITreeData> dataList = new ArrayList<DocsUITreeData>();
		for (ControllerInfo info : m.values()) {
			String[] paths = info.getDir().split("/");
			convertUIData(dataList, paths, 0, "", methodInfoMap);
		}
		
		DocsBasicInfo.DocsInfo.setDocData(dataList);
		DocsBasicInfo.DocsInfo.setSuccess(true);
		
		log.info("data:{}",JSON.toJSONString(dataList));

	}

	
	/**
	 * 转换为 UI需要展示的数据格式
	 * @param dataList
	 * @param paths
	 * @param index
	 * @param parentPath
	 * @param methodInfoMap
	 */
	private static void convertUIData(List<DocsUITreeData> dataList, String[] paths, int index, String parentPath,
			Map<String, List<MethodInfo>> methodInfoMap) {
		if (index >= paths.length) {
			return;
		}

		String path = paths[index];
		String name = parentPath + path;
		DocsUITreeData data = null;
		for (DocsUITreeData d : dataList) {
			if (d.getTitle().equals(path)) {
				data = d;
				break;
			}
		}

		if (data == null) {
			data = new DocsUITreeData();
			data.setTitle(path);
			List<MethodInfo> methodInfoList = methodInfoMap.get(name);
			if (methodInfoList != null) {
				for (MethodInfo methodInfo : methodInfoList) {
					DocsUITreeData tmp = new DocsUITreeData();
					tmp.setTitle(methodInfo.getTags());
					tmp.setMethodInfo(methodInfo);
					data.getChildren().add(tmp);
				}

			}

			dataList.add(data);
		}

		convertUIData(data.getChildren(), paths, index + 1, name, methodInfoMap);
	}

}
